package com.sxu.search.binary;

/**
 * 二分查找
 *  时间复杂度：O（logN）
 *  空间复杂度：O（1）
 *  适用：有序数组
 */
public class BinarySearch {
    // 一般实现
    public static int binarySearch(int[] arr, int target) {
        int left = 0;
        int right = arr.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if(arr[mid] == target){
                return mid;
            } else if(arr[mid] < target){
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return -1;
    }

    // 递归实现
    public static int binarySearch2(int[] arr, int target, int left, int right) {
        // 判断边界情况
        if(left > right){
            return -1;
        }
        int mid = left + (right - left) / 2;
        if(arr[mid] == target){
            return mid;
        } else if(arr[mid] < target){
            return binarySearch2(arr, target, mid + 1, right);
        } else {
            return binarySearch2(arr, target, left, mid - 1);
        }
    }
}
